package com.board.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.board.client.UserServiceClient;
import com.board.client.dto.UserDto;
import com.board.dao.*;
import com.board.dto.FoodOrderDto;
import com.board.dto.OrderCommentDto;
import com.board.dto.StoreReplyDto;
import com.board.entity.*;
import com.board.exception.OrderCommentException;
import com.board.param.FindStoreCommentParam;
import com.board.param.StoreCommentReplyParam;
import com.board.param.UserCommentParam;
import com.board.param.UserFindCommentParam;
import com.board.service.OrderCommentService;
import com.board.service.SeatEatOrderService;
import com.board.util.PageInfo;
import com.board.util.Result;
import com.board.util.StateDate;
import jdk.nashorn.internal.runtime.regexp.joni.WarnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.ApiIgnore;

import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 膳食系统-订单评价表 服务实现类
 * </p>
 *
 * @author 小叶
 * @since 2024年04月04日
 */
@Service
public class OrderCommentServiceImpl extends ServiceImpl<OrderCommentMapper, OrderComment> implements OrderCommentService {
    @Autowired
    private OrderCommentMapper orderCommentMapper;
    @Autowired
    private SeatEatOrderMapper seatEatOrderMapper;
    @Autowired
    private SendOrderMapper sendOrderMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Override
    public OrderCommentDto userCommentOrder(UserCommentParam param, Integer userId) {
        //订单类型只能是0或1
        if (param.getOrderType()!=0&&param.getOrderType()!=1){
            throw new OrderCommentException(500,"订单类型错误");
        }
        //用户不能重复评价
        OrderComment one = orderCommentMapper.selectOne(new QueryWrapper<OrderComment>().eq("order_num", param.getOrderNum()).eq("user_or_store", 0));
        if (one!=null) throw new OrderCommentException(500,"用户不能重复评价");
        //订单是否存在及是否是用户的
        if (param.getOrderType()==0){
            //堂食订单
            SeatEatOrder order = seatEatOrderMapper.selectById(param.getOrderNum());
            if (order==null) throw new OrderCommentException(500,"订单不存在");
            if (order.getUserId()!=userId) throw new OrderCommentException(500,"订单不属于用户");
            //订单状态必须是已取餐才能进行评价
            if (order.getOrderState()!= StateDate.SEAT_ORDER_STATE_GET_FOOD){
                throw new OrderCommentException(500,"订单状态错误");
            }
        }else{
            SendOrder order = sendOrderMapper.selectById(param.getOrderNum());
            if (order==null) throw new OrderCommentException(500,"订单不存在");
            if (order.getUserId()!=userId) throw new OrderCommentException(500,"订单不属于用户");
            if (order.getOrderState()!= StateDate.SEND_ORDER_STATE_GET_FOOD){
                throw new OrderCommentException(500,"订单状态错误");
            }
        }
        List<OrderDetail> details = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_num", param.getOrderNum()));
        Result<UserDto> user = userServiceClient.findUserById(userId);
        if (user.getCode()!=200){
            throw new OrderCommentException(user.getCode(),user.getMessage());
        }
        //可以进行评价订单
        OrderComment orderComment = BeanUtil.toBean(param, OrderComment.class);
        orderComment.setUserId(userId);
        orderComment.setUserOrStore(0);
        orderComment.setCommentId(0);
        orderComment.setReplyId(details.get(0).getStoreId());
        orderComment.setCreateTime(LocalDateTime.now().toString());
        if (param.getIsAnnoy()==StateDate.COMMENT_IS_ANONYMOUS_YES){
            //匿名评价
            orderComment.setCommentName("匿名用户");
        }else{
            //非匿名
            orderComment.setCommentName(user.getData().getUserName());
        }
        orderCommentMapper.insert(orderComment);
        //订单日志表插入评价数据
        OrderLog orderLog = new OrderLog();
        orderLog.setLogDesc("用户评价订单");
        orderLog.setLogUser(user.getData().getUserName());
        orderLog.setOrderNum(param.getOrderNum());
        orderLog.setLogTime(LocalDateTime.now().toString());
        orderLog.setOrderType(StateDate.ORDER_TYPE_SEAT);
        orderLogMapper.insert(orderLog);
        //计算商家评分


        //返回数据
        OrderCommentDto dto = BeanUtil.toBean(orderComment, OrderCommentDto.class);
        dto.setFoodList(BeanUtil.copyToList(details, FoodOrderDto.class));
        return dto;
    }

    @Override
    public OrderCommentDto userDelComment(Integer commentId, Integer userId) {
        //用户删除评价，先查询评价是否存在
        OrderComment comment = orderCommentMapper.selectById(commentId);
        if (comment==null) throw new OrderCommentException(500,"评价不存在");
        //评价是否是登录用户的
        if (comment.getUserId()!=userId) throw new OrderCommentException(500,"评价不属于用户");
        //可以进行删除
        orderCommentMapper.deleteById(commentId);
        //如果商家回复了还要删除对应的回复内容
        QueryWrapper<OrderComment> wrapper = new QueryWrapper<>();
        wrapper.eq("order_num",comment.getOrderNum());
        wrapper.eq("user_or_store",1);
        OrderComment orderComment = orderCommentMapper.selectOne(wrapper);
        if (orderComment!=null){
            orderCommentMapper.deleteById(orderComment.getId());
        }
        //计算评分

        //返回数据
        OrderCommentDto dto = BeanUtil.toBean(comment, OrderCommentDto.class);
        return dto;
    }

    @Override
    public StoreReplyDto storeComment(StoreCommentReplyParam param, Integer storeId) {
        //商家回复评价:回复的评价是否存在
        OrderComment orderComment = orderCommentMapper.selectById(param.getId());
        if (orderComment==null) throw new OrderCommentException(500,"评价不存在");
        //评价的订单是否是商家的
        List<OrderDetail> details = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_num", orderComment.getOrderNum()));
        if (details.get(0).getStoreId()!=storeId) throw new OrderCommentException(500,"订单不属于该商家");
        //商家回复过不能再次回复
        OrderComment one = orderCommentMapper.selectOne(new QueryWrapper<OrderComment>().eq("order_num", orderComment.getOrderNum()).eq("user_or_store", 1));
        if (one!=null) throw new OrderCommentException(500,"商家已经回复过评价");
        //可以进行回复
        OrderComment comment = new OrderComment();
        comment.setOrderNum(orderComment.getOrderNum());
        comment.setCotent(param.getCotent());
        comment.setUserId(storeId);
        comment.setCommentId(param.getId());
        comment.setReplyId(orderComment.getUserId());
        comment.setOrderType(orderComment.getOrderType());
        comment.setUserOrStore(1);
        comment.setCommentName("商家回复");
        comment.setCreateTime(LocalDateTime.now().toString());
        orderCommentMapper.insert(comment);
        //插入日志记录
        OrderLog orderLog = new OrderLog();
        orderLog.setLogTime(LocalDateTime.now().toString());
        orderLog.setOrderNum(orderComment.getOrderNum());
        orderLog.setLogUser("商家");
        orderLog.setLogDesc("商家回复评价");
        orderLog.setOrderType(orderComment.getOrderType());
        orderLogMapper.insert(orderLog);
        StoreReplyDto dto = BeanUtil.toBean(orderComment, StoreReplyDto.class);
        dto.setFoodList(BeanUtil.copyToList(details, FoodOrderDto.class));
        dto.setReplyCotent(param.getCotent());
        return dto;
    }

    @Override
    public OrderCommentDto findCommentById(Integer id) {
        OrderComment orderComment = orderCommentMapper.selectById(id);
        if (orderComment==null) throw new OrderCommentException(500,"评价不存在");
        OrderCommentDto dto = BeanUtil.toBean(orderComment, OrderCommentDto.class);
        List<OrderDetail> details = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_num", orderComment.getOrderNum()));
        dto.setFoodList(BeanUtil.copyToList(details, FoodOrderDto.class));
        return dto;
    }

    @Override
    public PageInfo<OrderCommentDto> userFindComment(UserFindCommentParam param, Integer userId) {
        //传递进来的参数都是0或1
        if (param.getIsSatisfy()!=null){
            if (param.getIsSatisfy()!=0 && param.getIsSatisfy()!=1){
                throw new OrderCommentException(500,"是否满意参数错误");
            }
        }
        if (param.getHasImg()!=null){
            if (param.getHasImg()!=0 && param.getHasImg()!=1){
                throw new OrderCommentException(500,"是否有图参数错误");
            }
        }
        //查询
        Page<OrderComment> page = new Page<>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 5 : param.getPageSize());
        QueryWrapper<OrderComment> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("user_or_store",0);
        if (param.getIsSatisfy()!=null){
            if (param.getIsSatisfy()==0){
                //满意
                wrapper.ge("level",3);
            }else{
                //不满意
                wrapper.lt("level",3);
            }
        }
        if (param.getHasImg()!=null){
            if (param.getHasImg()==0){
                //有图
                wrapper.ne("comment_img","");
            }else{
                //没有图
                wrapper.eq("comment_img","");
            }
        }
        orderCommentMapper.selectPage(page,wrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        List<OrderComment> comments = page.getRecords();
        List<OrderCommentDto> dtos = BeanUtil.copyToList(comments, OrderCommentDto.class);
        for (OrderCommentDto dto : dtos) {
            List<OrderDetail> details = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_num", dto.getOrderNum()));
            dto.setFoodList(BeanUtil.copyToList(details, FoodOrderDto.class));
            //查询商家是否有回复该条评论
            QueryWrapper<OrderComment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_num",dto.getOrderNum());
            queryWrapper.eq("user_or_store",1);
            OrderComment orderComment = orderCommentMapper.selectOne(queryWrapper);
            if (orderComment!=null){
                dto.setReplyContent(orderComment.getCotent());
                dto.setReplyCreateTime(orderComment.getCreateTime());
            }
        }
        pageInfo.setList(dtos);
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }

    @Override
    public PageInfo<OrderCommentDto> storeFindComment(FindStoreCommentParam param) {
        //传递进来的参数都是0或1
        if (param.getIsSatisfy()!=null){
            if (param.getIsSatisfy()!=0 && param.getIsSatisfy()!=1){
                throw new OrderCommentException(500,"是否满意参数错误");
            }
        }
        if (param.getHasImg()!=null){
            if (param.getHasImg()!=0 && param.getHasImg()!=1){
                throw new OrderCommentException(500,"是否有图参数错误");
            }
        }
        //查询
        Page<OrderComment> page = new Page<>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 5 : param.getPageSize());
        QueryWrapper<OrderComment> wrapper = new QueryWrapper<>();
        wrapper.eq("reply_id",param.getStoreId());
        wrapper.eq("comment_id",0);
        if (param.getIsSatisfy()!=null){
            if (param.getIsSatisfy()==0){
                //满意
                wrapper.ge("level",3);
            }else{
                //不满意
                wrapper.lt("level",3);
            }
        }
        if (param.getHasImg()!=null){
            if (param.getHasImg()==0){
                //有图
                wrapper.ne("comment_img","");
            }else{
                //没有图
                wrapper.eq("comment_img","");
            }
        }
        orderCommentMapper.selectPage(page,wrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        List<OrderComment> comments = page.getRecords();
        List<OrderCommentDto> dtos = BeanUtil.copyToList(comments, OrderCommentDto.class);
        for (OrderCommentDto dto : dtos) {
            List<OrderDetail> details = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_num", dto.getOrderNum()));
            dto.setFoodList(BeanUtil.copyToList(details, FoodOrderDto.class));
            //查询商家是否有回复该条评论
            QueryWrapper<OrderComment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_num",dto.getOrderNum());
            queryWrapper.eq("user_or_store",1);
            OrderComment orderComment = orderCommentMapper.selectOne(queryWrapper);
            if (orderComment!=null){
                dto.setReplyContent(orderComment.getCotent());
                dto.setReplyCreateTime(orderComment.getCreateTime());
            }
        }
        pageInfo.setList(dtos);
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }
}
